package com.example.myapplication01.service.tinno.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class MyService extends Service {

    private MyBinder myBinder = new MyBinder();
    private Thread thread;
    private volatile boolean flag = false;

    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        thread = new Thread(() -> {
            while (!flag) {
                try {
                    Thread.sleep(1000);
                    Log.i("MyService","run");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    // 绑定的时候返回通信载体（myBinder）即可
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("MyService", "onBind: onBind()");
        return myBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("MyService", "onUnbind: onUnbind()");
        super.onDestroy();
        flag = true;
        if (thread != null) {
            thread.interrupt();
        }
        return super.onUnbind(intent);
    }

    public void test() {
        Log.d("MyService", "test: test()");
    }

    // 用作客户端（activity）与service通信的
    public class MyBinder extends Binder {

        // 调用service的方法
        public void callServiceTestMethod() {
            test();
        }
    }
}